package com.situ.servlet;

import com.alibaba.fastjson2.JSON;
import com.situ.pojo.Student;
import com.situ.pojo.search.StudentDTO;
import com.situ.service.StudentService;
import com.situ.service.impl.StudentServiceImpl;
import com.situ.util.BeanFactory;
import com.situ.util.Pagination;
import com.situ.util.ServletUtils;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/student/*")
public class StudentServlet extends HttpServlet {
    private StudentService studentService = BeanFactory.getBean(StudentServiceImpl.class);
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getPathInfo();
            if ("/add".equals(action)){
                RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/student/add.jsp");
                dispatcher.forward(req,resp);
            }
            else if ("/edit".equals(action)) {
                String id = req.getParameter("id");
//                System.out.println(id); id取到  OK
                req.setAttribute("id",id);
                RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/student/edit.jsp");
                dispatcher.forward(req,resp);
            }
            else if ("/id".equals(action)) {
                //回显
                String id = req.getParameter("id");
                Student student = studentService.findById(Integer.parseInt(id));
                System.out.println("id"+student);
                ServletUtils.renderJson(resp,Map.of("student",student));

            }
            else {
                RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/jsp/student/list.jsp");
                dispatcher.forward(req,resp);
            }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取额外的路径信息 不包括在配置的路径信息内部的信息
        String action = req.getPathInfo();
        if ("/list".equals(action)){
            list(req, resp);
        } else if ("/delete".equals(action)) {
            deleteByIds(req,resp);
        } else if ("/add".equals(action)) {
           //新增
            addStudent(req,resp);
        }else if ("/edit".equals(action)) {
//            String name = req.getParameter("name");
//            System.out.println(name);
            //新增
            editStudent(req,resp);
        }
    }
    private void list(HttpServletRequest req, HttpServletResponse resp){
        //获取数据
//            List<Student> studentList = studentService.findAll();
        String page = req.getParameter("page");//页码
        String limit = req.getParameter("limit");//每页展示的条数
        //前端传递的数据
        String cardId = req.getParameter("cardId");
        String name= req.getParameter("name");
        String sex= req.getParameter("sex");
        String phone= req.getParameter("phone");
        String birthStart= req.getParameter("birthStart");
        String birthEnd= req.getParameter("birthEnd");
        //查询条件封装
        StudentDTO condition = new StudentDTO();
        if (StringUtils.hasText(cardId)){
            condition.setCardId(cardId);
        }
        if (StringUtils.hasText(name)){
            condition.setName(name);
        }
        if (StringUtils.hasText(sex)){
            condition.setSex(sex);
        }
        if (StringUtils.hasText(phone)){
            condition.setPhone(phone);
        }
        if (StringUtils.hasText(birthStart)){
            condition.setBirthStart(LocalDate.parse(birthStart, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
        if (StringUtils.hasText(birthEnd)){
            condition.setBirthEnd(LocalDate.parse(birthEnd, DateTimeFormatter.ofPattern("yyyy-MM-dd")));
//                condition.setBirthEnd(LocalDate.parse(birthEnd,DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }


        Pagination pagination = null;
        try {
            pagination = new Pagination(Integer.parseInt(page),Integer.parseInt(limit));
        } catch (NumberFormatException e) {
            pagination = new Pagination(1,20);
        }
        List<Student> studentList = studentService.findAll(pagination, condition);
        Map<String, Object> map=Map.of("studentList",studentList,"pi",pagination);
//            System.out.println(pagination.getPages());

        resp.setContentType("application/json;charset=UTF-8");
        //请求转发
        String json = JSON.toJSONString(map);
        PrintWriter out = null;
        try {
            out = resp.getWriter();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        out.write(json);
        out.flush();
    }

    private void deleteByIds(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String[] ids = req.getParameterValues("ids");
        System.out.println(Arrays.toString(ids));
        List<Integer> integers = new ArrayList<>();
        for (String id : ids) {
            integers.add(Integer.parseInt(id));
        }
        int row=studentService.deleteByIds(integers);
        Map<String, Object> map = Map.of("rows", row);
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write(JSON.toJSONString(map));
        writer.flush();
    }
    private void addStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name=req.getParameter("name");
        String cardId=req.getParameter("cardId");
        String sex=req.getParameter("sex");
        String phone=req.getParameter("phone");
        String pinyin=req.getParameter("pinyin");
        String weixin=req.getParameter("weixin");
        String birth=req.getParameter("birthday");
        Student student = new Student();
        student.setName(name);
        student.setCardId(cardId);
        if (!sex.equals("男")&&!sex.equals("女")){
            ServletUtils.renderJson(resp,Map.of("error","不合法"));
            return;
        }
        student.setSex(sex);
        student.setPhone(phone);
        student.setPinyin(pinyin);
        student.setWeixin(weixin);
        student.setBirthday(LocalDate.parse(birth,DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //调用业务类
        boolean add = studentService.add(student);
        System.out.println(add);
        ServletUtils.renderJson(resp,Map.of("success",add));
    }

    private void editStudent(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        System.out.println("要修改的id为"+id);
        String name=req.getParameter("name");
        String cardId=req.getParameter("cardId");
        String sex=req.getParameter("sex");
        String phone=req.getParameter("phone");
        String pinyin=req.getParameter("pinyin");
        String weixin=req.getParameter("weixin");
        String birth=req.getParameter("birthday");
        Student student = new Student();
        student.setId(Integer.parseInt(id));
        student.setName(name);
        student.setCardId(cardId);
        if (!sex.equals("男")&&!sex.equals("女")){
            ServletUtils.renderJson(resp,Map.of("error","不合法"));
            return;
        }
        student.setSex(sex);
        student.setPhone(phone);
        student.setPinyin(pinyin);
        student.setWeixin(weixin);
        student.setBirthday(LocalDate.parse(birth,DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        //调用业务类
        boolean add = studentService.edit(student);
        System.out.println(add);
        ServletUtils.renderJson(resp,Map.of("success",add));
    }

}
//保存学生

